package model

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"missC/config"
	"missC/utils/er"
	log "missC/utils/logs"
	"time"
)

var db *gorm.DB //使用全局变量
var err error   //使用全局变量
func DbInit() {

	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		config.MysqlName, config.MysqlPassword, config.MysqlHost, config.MysqlPort, config.MysqlDb)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // use singular table name, table for `User` would be `user` with this option enabled
		},
	})
	if err != nil {
		log.Error(er.GetErr(213))
		return
	}

	//配置sql连接池
	dbdql, _ := db.DB()
	dbdql.SetMaxIdleConns(10)                  //空闲连接数10
	dbdql.SetMaxOpenConns(100)                 //数据库最大连接数100
	dbdql.SetConnMaxLifetime(10 * time.Second) //最大复用时间10秒
	// 迁移 schema
	_ = db.AutoMigrate(&User{}, &Article{}, &Sort{})

	//Db.Create(&user)

}

/*func Close() {
	_ = dbsql.Close() //不处理它的返回错误使用 _
}*/
